/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.util.List;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import frames.WriteGroupsToXMLwithFrames;
import getData.GetDataFromFieldsOfFramesXML;

/**
 *
 * @author AKiselev
 */
@SuppressWarnings("serial")
public class FramesInFrame extends javax.swing.JFrame {

    private static String nameOfFrameWhereWeWillBeManagingFields;
	private static List<String> listOfAllFieldsInThisForAdding;
	private static List<String> listOfAllAlreadyAddedFieldsInThisFrame;
	private static String[] listofFieldsAlreadyaddedInFrame;
	private static String[] listofFieldsInFrame;
	private static String nameOfXMLForFrameWhereWeWillBeManagingFields;
	private static String nameOfXMLForFrameWithFieldsForAdding;
	private static String nameOfFrameForManagingFields;
	/**
     * Creates new form FramesInFrame
     */
    public FramesInFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButtonSave = new javax.swing.JButton();
        jButtonClose = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jSeparator2 = new javax.swing.JSeparator();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        DeleteFieldFromList = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jComboBoxFieldToInclude = new javax.swing.JComboBox();
        new javax.swing.JLabel();
        jButtonAddField = new javax.swing.JButton();
        
        setTitle(nameOfFrameWhereWeWillBeManagingFields);
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButtonSave.setText("Save and quit");
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });

        jButtonClose.setText("Cancel");
        jButtonClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCloseActionPerformed(evt);
            }
        });

        updateListOfAddedFields();
        jScrollPane1.setViewportView(jList1);

        jButton1.setText("Up");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Down");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        DeleteFieldFromList.setText("Delete");
        DeleteFieldFromList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteFieldFromListActionPerformed(evt);
            }
        });

        jLabel1.setText("Select field to include");

        jComboBoxFieldToInclude.setModel(new javax.swing.DefaultComboBoxModel(listofFieldsInFrame));

        //nameOfCurrentFrameInFrame.setText("Current frame: " + nameOfFrameWhereWeWillBeManagingFields);

        jButtonAddField.setText("Add field to list");
        jButtonAddField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddFieldActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButtonSave)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonClose))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(DeleteFieldFromList))
                           // .addComponent(nameOfCurrentFrameInFrame)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(28, 28, 28)
                                .addComponent(jComboBoxFieldToInclude, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonAddField)))
                        .addGap(0, 11, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
          //      .addComponent(nameOfCurrentFrameInFrame)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jComboBoxFieldToInclude, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonAddField))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(DeleteFieldFromList))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonSave)
                    .addComponent(jButtonClose))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void updateListOfAddedFields() {
		jList1.setModel(new javax.swing.AbstractListModel() {
            /**
			 * 
			 */
			private static final long serialVersionUID = 1401002130931949439L;
			//String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return listofFieldsAlreadyaddedInFrame.length; }
            public Object getElementAt(int i) { return listofFieldsAlreadyaddedInFrame[i]; }
		});
	}

    private void jButtonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCloseActionPerformed
    	setVisible(false); 
    	dispose(); // not sure
    	FieldsInFrames newFrame = new FieldsInFrames();
    	newFrame.setVisible(true);
    	//newFrame.main(null);
    }//GEN-LAST:event_jButtonCloseActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    	//pull up
    	int indexOfField = -1;
    	indexOfField = jList1.getSelectedIndex();
    	String nameOfField = (String) jList1.getSelectedValue();
    	
    	checkIfThereIsNoSelectedFieldInList(indexOfField);
    	
    	checkIfThereIsOnlyOneFieldInList(indexOfField);
    	
    	if ((indexOfField == 0) && (listofFieldsAlreadyaddedInFrame.length > 1)){
    		JOptionPane.showMessageDialog(new JFrame(), "You can't move first field, it's already upper", "Error",
			        JOptionPane.ERROR_MESSAGE);
    		}
    	
    	if ((listofFieldsAlreadyaddedInFrame.length >= 1) && (indexOfField > 0)){
    		String cashedField = listOfAllAlreadyAddedFieldsInThisFrame.get(indexOfField - 1);
    		listOfAllAlreadyAddedFieldsInThisFrame.set(indexOfField - 1, nameOfField);
    		listOfAllAlreadyAddedFieldsInThisFrame.set(indexOfField, cashedField);
    		listofFieldsAlreadyaddedInFrame = listOfAllAlreadyAddedFieldsInThisFrame.toArray(new String[listOfAllAlreadyAddedFieldsInThisFrame.size()]);
    		updateListOfAddedFields();
    		jList1.setSelectedValue(nameOfField, true);
    	}
    	
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // pull down
    	int indexOfField = -1;
    	indexOfField = jList1.getSelectedIndex();
    	String nameOfField = (String) jList1.getSelectedValue();
    	
    	checkIfThereIsNoSelectedFieldInList(indexOfField);
    		
    	checkIfThereIsOnlyOneFieldInList(indexOfField);
    	//System.out.println(indexOfField + " = " + listofFieldsAlreadyaddedInFrame.length);
    	if ((indexOfField == (listofFieldsAlreadyaddedInFrame.length - 1)) && (listofFieldsAlreadyaddedInFrame.length > 1)){
    		JOptionPane.showMessageDialog(new JFrame(), "You can't move first field, it's already in the end of list", "Error",
			        JOptionPane.ERROR_MESSAGE);
    		}
    	
    	if ((listofFieldsAlreadyaddedInFrame.length >= 1) && (indexOfField < (listofFieldsAlreadyaddedInFrame.length - 1))){
    		String cashedField = listOfAllAlreadyAddedFieldsInThisFrame.get(indexOfField + 1);
    		listOfAllAlreadyAddedFieldsInThisFrame.set(indexOfField + 1, nameOfField);
    		listOfAllAlreadyAddedFieldsInThisFrame.set(indexOfField, cashedField);
    		listofFieldsAlreadyaddedInFrame = listOfAllAlreadyAddedFieldsInThisFrame.toArray(new String[listOfAllAlreadyAddedFieldsInThisFrame.size()]);
    		updateListOfAddedFields();
    		jList1.setSelectedValue(nameOfField, true);
    	}
    	
    }//GEN-LAST:event_jButton2ActionPerformed



    private void DeleteFieldFromListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteFieldFromListActionPerformed
       	String nameOfDeletingField = (String) jComboBoxFieldToInclude.getSelectedItem();
    	listOfAllAlreadyAddedFieldsInThisFrame.clear();
    	for (String selectedField : listofFieldsAlreadyaddedInFrame) {
			if (nameOfDeletingField.equals(selectedField)){}
    		else {
    			listOfAllAlreadyAddedFieldsInThisFrame.add(selectedField);
    			//System.out.println("listOfAllAlreadyAddedFieldsInThisFrame " + listOfAllAlreadyAddedFieldsInThisFrame.toString());
    			listofFieldsAlreadyaddedInFrame = listOfAllAlreadyAddedFieldsInThisFrame.toArray(new String[listOfAllAlreadyAddedFieldsInThisFrame.size()]);
    			updateListOfAddedFields();
    			}
    		}
    }//GEN-LAST:event_DeleteFieldFromListActionPerformed

    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
        WriteGroupsToXMLwithFrames writeGroupsToXMLwithFrames = new WriteGroupsToXMLwithFrames();
        writeGroupsToXMLwithFrames.rewriteXMLlistOfFramesWithNewFrames(
        		listOfAllAlreadyAddedFieldsInThisFrame, listofFieldsAlreadyaddedInFrame,
        		nameOfXMLForFrameWhereWeWillBeManagingFields, nameOfFrameForManagingFields);
        jButtonCloseActionPerformed(evt);
    }//GEN-LAST:event_jButtonSaveActionPerformed

    private void jButtonAddFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddFieldActionPerformed
       	String nameOfNewField = (String) jComboBoxFieldToInclude.getSelectedItem();
    	boolean systemFindDuplicate = false;
    	
    	for (String selectedField : listofFieldsAlreadyaddedInFrame) {
			if (nameOfNewField.equals(selectedField)){
				JOptionPane.showMessageDialog(new JFrame(), "This frame is already exists", "Error",
				        JOptionPane.ERROR_MESSAGE);
				systemFindDuplicate = true;
				break;
			}
		}
    	if (!systemFindDuplicate){ 
    		listOfAllAlreadyAddedFieldsInThisFrame.add(nameOfNewField);
    	listofFieldsAlreadyaddedInFrame = listOfAllAlreadyAddedFieldsInThisFrame.toArray(new String[listOfAllAlreadyAddedFieldsInThisFrame.size()]);
    	updateListOfAddedFields();
    	}
    }//GEN-LAST:event_jButtonAddFieldActionPerformed
    
	private void checkIfThereIsOnlyOneFieldInList(int indexOfField) {
		if ((indexOfField != -1) && (listofFieldsAlreadyaddedInFrame.length <= 1)){
    		JOptionPane.showMessageDialog(new JFrame(), "There is only one field in list", "Error",
			        JOptionPane.ERROR_MESSAGE);
    		}
	}

	private void checkIfThereIsNoSelectedFieldInList(int indexOfField) {
		if (indexOfField == -1){
    		JOptionPane.showMessageDialog(new JFrame(), "Please, select field", "Error",
			        JOptionPane.ERROR_MESSAGE);
    		}
	}

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
    	
    	GetDataFromFieldsOfFramesXML getDataFromFieldsOfFramesXML = new GetDataFromFieldsOfFramesXML();
    	// name of XML, which we added to another Frame
    	nameOfXMLForFrameWithFieldsForAdding = "src/framesXML/First included frame (as a Table after fields).xml";
    	nameOfFrameForManagingFields = "First included frame (as a Table after fields)";
    	    	
    	//name of XML, to which we added frame
    	nameOfXMLForFrameWhereWeWillBeManagingFields = "src/framesXML/1. This is my first project.xml";
    	
    	
//    	String nameOfProjectWhereThisFramePlased = "1. This is my first project";
//    	String listOfProjectsFileName = "projects.xml";
    	
    	listOfAllFieldsInThisForAdding = getDataFromFieldsOfFramesXML.getListOfFieldsFromCurrentFrame(nameOfXMLForFrameWithFieldsForAdding, "Name of field");
    	listofFieldsInFrame = listOfAllFieldsInThisForAdding.toArray(new String[listOfAllFieldsInThisForAdding.size()]);
    	
    	listOfAllAlreadyAddedFieldsInThisFrame = getDataFromFieldsOfFramesXML.getListOfAlreadySelectedFields(nameOfXMLForFrameWhereWeWillBeManagingFields,nameOfFrameForManagingFields);
    	listofFieldsAlreadyaddedInFrame = listOfAllAlreadyAddedFieldsInThisFrame.toArray(new String[listOfAllAlreadyAddedFieldsInThisFrame.size()]);
    	
    	System.out.println("reading complete");
    	for (String string : listofFieldsAlreadyaddedInFrame) {
			System.out.println("string " + string);
		}
    	
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FramesInFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FramesInFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FramesInFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FramesInFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FramesInFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton DeleteFieldFromList;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButtonAddField;
    private javax.swing.JButton jButtonClose;
    private javax.swing.JButton jButtonSave;
    @SuppressWarnings("rawtypes")
	private javax.swing.JComboBox jComboBoxFieldToInclude;
    private javax.swing.JLabel jLabel1;
    @SuppressWarnings("rawtypes")
	private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    // End of variables declaration//GEN-END:variables
	private static String nameOfXMLForFrame;
}
